from pathlib import Path
import signal
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator
from gi.repository import GLib as glib

APPINDICATOR_ID = 'bluepower'


def main():
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    indicator = appindicator.Indicator.new(APPINDICATOR_ID, "bluepower-3",
                                           appindicator.IndicatorCategory.SYSTEM_SERVICES)
    periodic_check(indicator)
    glib.timeout_add_seconds(30, periodic_check, indicator)
    gtk.main()


def render_menu(indicator):
    stats = get_stats()
    if len(stats) > 0:
        indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
        indicator.set_menu(build_menu(stats))
        min_stat = min([s[2] for s in stats])
        if min_stat > 75:
            indicator.set_icon("bluepower-3")
        elif min_stat > 50:
            indicator.set_icon("bluepower-2")
        elif min_stat > 25:
            indicator.set_icon("bluepower-1")
        else:
            indicator.set_icon("bluepower-0")
    else:
        indicator.set_status(appindicator.IndicatorStatus.PASSIVE)


def periodic_check(indicator):
    render_menu(indicator)
    return True


def build_menu(stats):
    menu = gtk.Menu()
    for stat in stats:
        item = gtk.MenuItem(label="{}: {} {}%".format(
            stat[0], stat[1], stat[2]))
        item.set_sensitive(False)
        menu.append(item)
    menu.show_all()
    return menu


def quit(source):
    gtk.main_quit()


def format_stat(hid):
    with (hid / "model_name").open("r") as f:
        model_name = f.read().strip()
    with (hid / "status").open("r") as f:
        status = f.read().strip()
    with (hid / "capacity").open("r") as f:
        capacity = f.read().strip()
    return (model_name, status, int(capacity))


def get_stats():
    p = Path("/sys/class/power_supply/")
    hids = [x for x in p.iterdir() if "hid" in x.name and "battery" in x.name]
    statuses = [format_stat(hid) for hid in hids]
    return statuses
